package com.vanrui.pcp.autocode.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.vanrui.pcp.autocode.model.entry.Field;
import com.vanrui.pcp.autocode.model.entry.JdbcConfig;

public class JDBCData {
	
	private final static Logger logger = Logger.getLogger(JDBCData.class);
	
	private JdbcConfig jdbcConfig;
	private String tableName;
	
	public JDBCData(JdbcConfig jdbcConfig, String tableName){
		this.jdbcConfig = jdbcConfig;
		this.tableName = tableName;
	}
	
	public List<Field> getTableFields() throws Exception{
		
		StringBuffer sql = new StringBuffer();
//		sql.append("select column_name,data_type,column_comment from information_schema.columns where table_name='").append(tableName).append("'").append(" group by column_name");
		sql.append("show full columns from ").append(tableName);
		Connection conn = JDBCUtil.getInstance(jdbcConfig).getConn();
		List<Field> fields = null;
		try {
			PreparedStatement pstm = conn.prepareStatement(sql.toString());
			ResultSet rs = pstm.executeQuery();
			if (rs != null) {
				fields = new ArrayList<Field>();
				while (rs.next()) {
					Field field = new Field();
					field.setColumnName(rs.getString("Field"));
					String type = rs.getString("Type");
					field.setColumnType(type.split("[(]")[0]);//bigint(20)只保留类型bigint
					field.setDefaultValue(rs.getString("Default"));
					field.setFieldComment(rs.getString("Comment"));
					fields.add(field);
				}
			}
		} catch (SQLException e) {
			logger.error("查询表字段操作异常");
			throw new Exception(e);
		}
		return fields;
	}

	public JdbcConfig getJdbcConfig() {
		return jdbcConfig;
	}

	public void setJdbcConfig(JdbcConfig jdbcConfig) {
		this.jdbcConfig = jdbcConfig;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

}
